import React, { Component } from 'react';
import styles from './index.module.scss'

// 吸顶组件
class Affix extends Component {
    placeholderRef = React.createRef()
    contentRef = React.createRef()

    // 监听滚动事件
    onWindowScroll = () => {
        const { top } = this.placeholderRef.current.getBoundingClientRect()

        console.log(top, "top")
        if (top < 0) {
            // 内容部分要进行固定定位
            this.contentRef.current.classList.add(styles.fixed)

            this.placeholderRef.current.style.height = '80px'
        } else {
            // 内容部分要进行固定定位
            this.contentRef.current.classList.remove(styles.fixed)

            this.placeholderRef.current.style.height = '0px'
        }
    }
    componentDidMount() {
        window.addEventListener('scroll', this.onWindowScroll)
    }
    componentWillUnmount() {
        window.removeEventListener('scroll',this.onWindowScroll)
    }
    render() {
        return (
            <div>
                {/* 占位视图 */}
                <div ref={this.placeholderRef}></div>
                <div ref={this.contentRef}>
                    {this.props.children}
                </div>
            </div>
        );
    }
}

export default Affix;
